%LAB 9
%CODE 1:generating dehraded image g;

f=imread('bits.jpg');
F=fft2(double(f));%To avoid convolution,taking image in fourier domain
FC=fftshift(F);
[m n]=size(f);
k=0.0025;%taking given value
for u=1:m
    for v=1:n
        H(u,v) = exp(-k*[(u-m/2)^2 + (v-n/2)^2]^(5/2));
end
end
g1=FC .* H;
g2=fftshift(g1);
g=ifft2(g2);
g3=real(g);
figure,imshow(real(g),[]);

%Exercise 1:Performing inverse filtering on g in Fourier domain with H.


for u=1:m
    for v=1:n
        if(H(u,v) ~= 0)
        F1(u,v)=g1(u,v) / H(u,v);
        else
            F1(u,v)=g1(u,v);%ignoring zeros of H
        end 
    end
end
FF1=ifft2(fftshift(F1));
figure,imshow(real(FF1),[]);



%Exercise 2:Apply a lowpass butterworth filter of order 10 to G/H, 
%trying out different values of the radius D0 and find the best radius.

%Butterworth filter
[m n]=size(F1);
d0 = 0.05*n % example: 5% of vertical size.
for u=1:m
    for v=1:n
     d = sqrt((u-m)^2 + (v-n)^2);
     H1(u,v) = 1/(1+(d/d0)^20);
    end
end

for u=1:m
       for v=1:n
           FF2(u,v)=F1(u,v) * H1(u,v);
       end
end

FF3=ifft2(fftshift(FF2));
figure,imshow(real(FF3),[]);



%Exercise 3:try out a Wiener filter on the image. 

PSF1=ifft2(fftshift(H));%taking PSF as centered H
PSF=real(PSF1);%The function deconvwnr takes real arguments
W=deconvwnr(g3,PSF,1);%trying different values of K,taking here as 1
figure,imshow(W);



%Exercise 4:
%Butterworth filtered image was a better version compared to the ful
%inverse which turned out to be too blurred .
